﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Telerik.WinControls.UI;
using Zvezda.FSO2.DB;
using Zvezda.FSO2.DB.DataSetFSOTableAdapters;

namespace FSO
{
    public partial class FormPaymentIn : Form, InterfaceObjDeleteableForm
    {
        DataSetFSO.PAYMENT_INRow _payInRow;

        public FormPaymentIn(int? pid)
        {
            InitializeComponent();

            _payInRow = dataSetFSO1.PAYMENT_IN.NewPAYMENT_INRow();

            //Полю "Дата" по умолчанию присваиваем сегодняшнее число
            _payInRow.DATE = DateTime.Now.Date;

            if (!pid.HasValue)
            {
                //это будут платежи за услуги

                _payInRow.TYPE = false;
            }
            else
            {
                CONTRACTTableAdapter taContract = new CONTRACTTableAdapter();
                
                _payInRow.PID = pid.Value;
                
                //Это платеж за товары
                _payInRow.TYPE = true;
                //по умолчанию присваиваем организацию из договора
                int orgId = taContract.GetDataByPID(_payInRow.PID).First().NSI_ORGANIZATION_ID;
                if(orgId > 0)
                {
                    _payInRow.NSI_ORGANIZATION_ID = orgId;
                }
                InitializeDirect(pid.Value);
            }

            dataSetFSO1.PAYMENT_IN.AddPAYMENT_INRow(_payInRow);
        }
        DIRECTTableAdapter directTableAdapter1;
        VIEW_DIRECT_ITEMTableAdapter vieW_DIRECT_ITEMTableAdapter1;
        DataSetFSO.DIRECTRow _directRow;
        private void InitializeDirect(int? pid)
        {
            if (pid == null)
            {

            }
            else
            {
                CONTRACTTableAdapter taContract = new CONTRACTTableAdapter();
                directTableAdapter1 = new DIRECTTableAdapter();
                vieW_DIRECT_ITEMTableAdapter1 = new VIEW_DIRECT_ITEMTableAdapter();
                vieW_DIRECT_ITEMTableAdapter1.ClearBeforeFill = true;
                directTableAdapter1.ClearBeforeFill = true;

                _directRow = dataSetFSO1.DIRECT.NewDIRECTRow();

                _directRow.PID = pid.Value;
                //Полю "Дата" по умолчанию присваиваем сегодняшнее число
                _directRow.DATE = DateTime.Now.Date;
                dataSetFSO1.DIRECT.AddDIRECTRow(_directRow);
            }
        }

        private void DeleteDirect()
        {
            if (_directRow != null)
            {
                _directRow.Delete();
                directTableAdapter1.Update(_directRow);
            }
        }

        public FormPaymentIn(DataSetFSO.PAYMENT_INRow row)
        {
            InitializeComponent();

            paymenT_INTableAdapter1.FillByID(dataSetFSO1.PAYMENT_IN, row.ID);
            _payInRow = dataSetFSO1.PAYMENT_IN.FindByID(row.ID);
            this.Text = "Платеж № " + _payInRow.NUMBER;
        }

        #region InterfaceObjectsMembers
        public int Delete()
        {
            _payInRow.Delete();

            //все связанные таблицы должны удаляться по констрейну в базе
            paymenT_INTableAdapter1.Update(_payInRow);
            //удаляем служебную записку
            DeleteDirect();
            this.Close();
            return 0;
        }

        public int Save()
        {
            int returnValue = -1;

            if (_payInRow.IsNUMBERNull())
            {
                MessageBox.Show(this, "Не заполнено обязательное поле \"Номер\".\nИзменения не будут сохранены", "Обязательное поле", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                
                //Сохранили саму строку
                paymenT_INTableAdapter1.Update(_payInRow);
                if (_directRow != null)
                {
                    _directRow.NUMBER = "СЗ_ПЛАТЕЖ_" + _payInRow.NUMBER;
                    //сохраняем служебную записку
                    directTableAdapter1.Update(_directRow);                    
                }
                PRODUCT_UNITTableAdapter taPU = new PRODUCT_UNITTableAdapter();
                //Если платеж не за услуги
                if (_payInRow.TYPE == true)
                {
                    #region Сохранения платежа не за услуги
                    //Сохраняем оплачиваемые товары
                    foreach (DataSetFSO.VIEW_PAY_IN_ITEMRow row in dataSetFSO1.VIEW_PAY_IN_ITEM.Rows)
                    {
                        DataSetFSO.PAYMENT_IN_ITEMRow payInItemRow;
                        DataSetFSO.PRODUCT_UNITRow productUnitRow;
                        if (row.RowState == DataRowState.Added)
                        {
                            payInItemRow = dataSetFSO1.PAYMENT_IN_ITEM.NewPAYMENT_IN_ITEMRow();
                            payInItemRow.PAYMENT_IN_ID = _payInRow.ID;
                            payInItemRow.PRODUCT_UNIT_ID = row.PRODUCT_UNIT_ID;
                            payInItemRow.PID = _payInRow.PID;
                            payInItemRow.SUM_CUR = row.SUM_CUR;
                            payInItemRow.SUM_RUB = row.SUM_RUB;
                            dataSetFSO1.PAYMENT_IN_ITEM.AddPAYMENT_IN_ITEMRow(payInItemRow);

                            paymenT_IN_ITEMTableAdapter1.Update(payInItemRow);
                            //сохраняем данные для служебной записки
                            if (_directRow != null)
                            {
                                productUnitRow = taPU.GetDataByID(row.PRODUCT_UNIT_ID).FindByID(row.PRODUCT_UNIT_ID);
                                if (productUnitRow.IsDIRECT_NUMBERNull())
                                {
                                    productUnitRow.DIRECT_NUMBER = _directRow.ID;
                                    taPU.Update(productUnitRow);
                                }
                            }
                        }
                        else if (row.RowState == DataRowState.Modified)
                        {
                            payInItemRow = paymenT_IN_ITEMTableAdapter1.GetDataByID(row.ID).FindByID(row.ID);
                            payInItemRow.SUM_CUR = row.SUM_CUR;
                            payInItemRow.SUM_RUB = row.SUM_RUB;
							//сохраняем данные для служебной записки
							if (_directRow != null)
							{
								productUnitRow = taPU.GetDataByID(row.PRODUCT_UNIT_ID).FindByID(row.PRODUCT_UNIT_ID);
								if (productUnitRow.IsDIRECT_NUMBERNull())
								{
									productUnitRow.DIRECT_NUMBER = _directRow.ID;
									taPU.Update(productUnitRow);
								}
							}
                            paymenT_IN_ITEMTableAdapter1.Update(payInItemRow);
                        }
                        else if (row.RowState == DataRowState.Deleted)
                        {
                            //Получаем данные удаленной строки из оригинальной версии (до удаления)
                            int rowId = (int)row[dataSetFSO1.VIEW_PAY_IN_ITEM.IDColumn, DataRowVersion.Original];
                            payInItemRow = paymenT_IN_ITEMTableAdapter1.GetDataByID(rowId).FindByID(rowId);
                            //сохраняем данные для служебной записки
                            if (_directRow != null)
                            {
                                productUnitRow = taPU.GetDataByID(payInItemRow.PRODUCT_UNIT_ID).FindByID(payInItemRow.PRODUCT_UNIT_ID);
								//Переводим товар в статус "Заказан" только в случае если удаляем его из того же платежа,
								//в котором он был переведен в производство
								if (!productUnitRow.IsDIRECT_NUMBERNull() && 
									 productUnitRow.DIRECT_NUMBER == _directRow.ID)
								{
									productUnitRow.SetDIRECT_NUMBERNull();
									taPU.Update(productUnitRow);
								}
                            }
                            payInItemRow.Delete();
                            paymenT_IN_ITEMTableAdapter1.Update(payInItemRow);
                            

                        }
                    }

                    //Сохраняем оплачиваемые счета
                    foreach (DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow row in dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.Rows)
                    {
                        DataSetFSO.PAY_IN_ON_INV_OUTRow payOnInv;
                        if (row.RowState == DataRowState.Added)
                        {
                            payOnInv = dataSetFSO1.PAY_IN_ON_INV_OUT.NewPAY_IN_ON_INV_OUTRow();
                            payOnInv.PAYMENT_IN_ID = _payInRow.ID;

                            payOnInv.INVOICE_OUT_ID = row.INVOICE_OUT_ID;
                            payOnInv.SUM_CUR = row.SUM_CUR;
                            payOnInv.SUM_RUB = row.SUM_RUB;
                            payOnInv.PID = _payInRow.PID;

                            dataSetFSO1.PAY_IN_ON_INV_OUT.AddPAY_IN_ON_INV_OUTRow(payOnInv);
                            paY_IN_ON_INV_OUTTableAdapter1.Update(payOnInv);
                        }
                        else if (row.RowState == DataRowState.Modified)
                        {
                            payOnInv = paY_IN_ON_INV_OUTTableAdapter1.GetDataByID(row.ID).FindByID(row.ID);
                            payOnInv.SUM_CUR = row.SUM_CUR;
                            payOnInv.SUM_RUB = row.SUM_RUB;

                            paY_IN_ON_INV_OUTTableAdapter1.Update(payOnInv);
                        }
                        else if (row.RowState == DataRowState.Deleted)
                        {
                            int id = (int)row[dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.IDColumn, DataRowVersion.Original];

                            payOnInv = paY_IN_ON_INV_OUTTableAdapter1.GetDataByID(id).FindByID(id);
                            payOnInv.Delete();

                            paY_IN_ON_INV_OUTTableAdapter1.Update(payOnInv);
                        }
                    }
                    #endregion
                }
                else
                {
                    //Если платеж за услуги
                    #region Сохранения платежа по услугам
                    //Сохраняем оплачиваемые услуги

                    PAY_IN_ON_SERVICETableAdapter ta = new PAY_IN_ON_SERVICETableAdapter();

                    foreach (DataSetFSO.VIEW_PAY_IN_ON_SERVICERow row in dataSetFSO1.VIEW_PAY_IN_ON_SERVICE.Rows)
                    {
                        DataSetFSO.PAY_IN_ON_SERVICERow payInOnServRow;
                        if (row.RowState == DataRowState.Added)
                        {
                            payInOnServRow = dataSetFSO1.PAY_IN_ON_SERVICE.NewPAY_IN_ON_SERVICERow();
                            payInOnServRow.PAYMENT_IN_ID = _payInRow.ID;
                            payInOnServRow.NSI_SERVICE_ID = row.NSI_SERVICE_ID;
                            //payInOnServRow.PID = _payInRow.PID;
                            payInOnServRow.QAUNTITY = row.QAUNTITY;
                            
                            dataSetFSO1.PAY_IN_ON_SERVICE.AddPAY_IN_ON_SERVICERow(payInOnServRow);

                            ta.Update(payInOnServRow);
                        }
                        else if (row.RowState == DataRowState.Modified)
                        {
                            payInOnServRow = ta.GetDataByID(row.ID).FindByID(row.ID);
                            payInOnServRow.QAUNTITY = row.QAUNTITY;
                            
                            ta.Update(payInOnServRow);
                        }
                        else if (row.RowState == DataRowState.Deleted)
                        {
                            //Получаем данные удаленной строки из оригинальной версии (до удаления)
                            int rowId = (int)row[dataSetFSO1.VIEW_PAY_IN_ON_SERVICE.IDColumn, DataRowVersion.Original];
                            payInOnServRow = ta.GetDataByID(rowId).FindByID(rowId);
                            payInOnServRow.Delete();

                            ta.Update(payInOnServRow);
                        }
                    }

                    //Сохраняем оплачиваемые счета
                    foreach (DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow row in dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.Rows)
                    {
                        DataSetFSO.PAY_IN_ON_INV_OUTRow payOnInv;
                        if (row.RowState == DataRowState.Added)
                        {
                            payOnInv = dataSetFSO1.PAY_IN_ON_INV_OUT.NewPAY_IN_ON_INV_OUTRow();
                            payOnInv.PAYMENT_IN_ID = _payInRow.ID;

                            payOnInv.INVOICE_OUT_ID = row.INVOICE_OUT_ID;
                            payOnInv.SUM_CUR = row.SUM_CUR;
                            payOnInv.SUM_RUB = row.SUM_RUB;
                            //payOnInv.PID = _payInRow.PID;

                            dataSetFSO1.PAY_IN_ON_INV_OUT.AddPAY_IN_ON_INV_OUTRow(payOnInv);
                            paY_IN_ON_INV_OUTTableAdapter1.Update(payOnInv);
                        }
                        else if (row.RowState == DataRowState.Modified)
                        {
                            payOnInv = paY_IN_ON_INV_OUTTableAdapter1.GetDataByID(row.ID).FindByID(row.ID);
                            payOnInv.SUM_CUR = row.SUM_CUR;
                            payOnInv.SUM_RUB = row.SUM_RUB;

                            paY_IN_ON_INV_OUTTableAdapter1.Update(payOnInv);
                        }
                        else if (row.RowState == DataRowState.Deleted)
                        {
                            int id = (int)row[dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.IDColumn, DataRowVersion.Original];

                            payOnInv = paY_IN_ON_INV_OUTTableAdapter1.GetDataByID(id).FindByID(id);
                            payOnInv.Delete();

                            paY_IN_ON_INV_OUTTableAdapter1.Update(payOnInv);
                        }
                    }

                    #endregion
                }

                RefreshForm();

                returnValue = 0;
            }

            return returnValue;
        }

        public int RefreshForm()
        {
            //Очищаем все таблицы
            foreach (DataTable table in dataSetFSO1.Tables)
            {
                if (!(table is DataSetFSO.PAYMENT_INDataTable || table is DataSetFSO.DIRECTDataTable))
                {
                    table.Clear();
                }
            }

            //Заполняем постоянные для конкретного платежа поля формы
            CONTRACTTableAdapter taContract = new CONTRACTTableAdapter();
            NSI_ORGANIZATIONTableAdapter taOrg = new NSI_ORGANIZATIONTableAdapter();   
            NSI_TYPE_OF_ACTIVITYTableAdapter taTypeOfAct = new NSI_TYPE_OF_ACTIVITYTableAdapter();

            //Находим контракт, в рамках которого создан платеж

            //Если платеж не за услуги, то указываем контракт и направление
            if (_payInRow.TYPE == true)
            {
                #region Обновление платежа не по услугам
                DataSetFSO.CONTRACTRow contract = taContract.GetDataByPID(_payInRow.PID).FirstOrDefault();
                radLabelContract.Text = contract.NUMBER;

                if (!contract.IsNSI_TYPE_OF_ACTIVITY_IDNull())
                {
                    radLabelTypeOfAct.Text = taTypeOfAct.GetData().FindByID(contract.NSI_TYPE_OF_ACTIVITY_ID).NAME;
                }
                else
                {
                    radLabelTypeOfAct.Text = "<Не указано>";
                }


                if (!_payInRow.IsNSI_ORGANIZATION_IDNull())
                {
                    radLabelOrganization.Text = taOrg.GetDataById(_payInRow.NSI_ORGANIZATION_ID).FindByID(_payInRow.NSI_ORGANIZATION_ID).SHORT_NAME;
                }
                else
                {
                    radLabelOrganization.Text = "<Не указана>";
                }

                //заполняем таблицу платежей по счету
                vieW_PAY_IN_ON_INV_OUTTableAdapter1.FillByPayInId(dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT, _payInRow.ID);

                //заполняем таблицу товаров платежа
                vieW_PAY_IN_ITEMTableAdapter1.FillByPayInID(dataSetFSO1.VIEW_PAY_IN_ITEM, _payInRow.ID);

                if (_directRow != null)
                {
                    dataSetFSO1.AGGR_PRODUCT_UNTS.Clear();
                    vieW_DIRECT_ITEMTableAdapter1.FillByDirectID(dataSetFSO1.VIEW_DIRECT_ITEM, _directRow.ID);
                }
                BindControls();
                InitializePaymentsGrid();
                InitializeProductsGrid();
                PaySummary();
                EvaluateRests();
                EvaluateAdvance();
                #endregion
            }
            else if(_payInRow.TYPE == false)
            {
                //Если платеж за услуги
                #region Обновление платежа по услугам
                if (!_payInRow.IsNSI_ORGANIZATION_IDNull())
                {
                    radLabelOrganization.Text = taOrg.GetDataById(_payInRow.NSI_ORGANIZATION_ID).FindByID(_payInRow.NSI_ORGANIZATION_ID).SHORT_NAME;
                }
                else
                {
                    radLabelOrganization.Text = "<Не указана>";
                }


                //заполняем таблицу платежей по счету

                vieW_PAY_IN_ON_INV_OUTTableAdapter1.FillByPayInId(dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT, _payInRow.ID);
                vieW_PAY_IN_ON_SERVICETableAdapter1.FillByPayID(dataSetFSO1.VIEW_PAY_IN_ON_SERVICE, _payInRow.ID);

                BindControls();

                InitializePaymentsGrid();
                IntializeServiceGrid();

                #endregion
            }
            return 0;
        }

        private void BindControls()
        {
            //Номер платежа
            radTextBoxNumber.DataBindings.Clear();
            radTextBoxNumber.DataBindings.Add("Text", _payInRow, dataSetFSO1.PAYMENT_IN.NUMBERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Дата
            radDateTimePickerDate.DataBindings.Clear();
            radDateTimePickerDate.DataBindings.Add("Value", _payInRow, dataSetFSO1.PAYMENT_IN.DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Сумма 
            radMaskedEditBoxSum.DataBindings.Clear();
            radMaskedEditBoxSum.DataBindings.Add("Text", _payInRow, dataSetFSO1.PAYMENT_IN.SUM_RUBColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged, 0, "N2");

            //Аванс доплата
            //Процент аванса
            //radMaskedEditBoxPercent.DataBindings.Clear();
            //radMaskedEditBoxPercent.DataBindings.Add("Text", _payInRow, dataSetFSO1.PAYMENT_IN.ADVANCE_PERCENTColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged, 0, "N2");

            ////Процент доплаты            
            //radMaskedEditBoxAddPayPercent.DataBindings.Clear();
            //radMaskedEditBoxAddPayPercent.DataBindings.Add("Text", _rowInvOut, dataSetFSO1.INVOICE_OUT.ADD_PAY_PERCENTColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged, 0, "N2");

            //Комментарии
            radTextBoxDescription.DataBindings.Clear();
            radTextBoxDescription.DataBindings.Add("Text", _payInRow, dataSetFSO1.PAYMENT_IN.DESCRIPTIONColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
        }

        public string FormName
        {
            get
            {
                string returnString = "Payment_In_";

                if (_payInRow.ID <= 0)
                {
                    returnString = returnString + DateTime.Now;
                }
                else
                {
                    returnString = returnString + _payInRow.ID;
                }

                return returnString;
            }
        }
        #endregion

        private void InitializeProductsGrid()
        {
            //Колонки для агрегированной таблицы

            //Название товара
            GridViewTextBoxColumn colProdName = new GridViewTextBoxColumn("AGGR_PRODUCT_NAME", dataSetFSO1.AGGR_PU_PAY_IN.NAMEColumn.ColumnName);
            colProdName.HeaderText = "Имя";
            colProdName.ReadOnly = true;

            //Количество товара
            GridViewTextBoxColumn colCount = new GridViewTextBoxColumn("AGGR_COUNT", dataSetFSO1.AGGR_PU_PAY_IN.COUNTColumn.ColumnName);
            colCount.HeaderText = "Кол.";
            colCount.ReadOnly = true;

            //Единица измерения
            GridViewTextBoxColumn colAggrNSIMeter = new GridViewTextBoxColumn("AGGR_NSI_METER", dataSetFSO1.AGGR_PU_PAY_IN.NSI_METER_NAMEColumn.ColumnName);
            colAggrNSIMeter.HeaderText = "ед.";
            colAggrNSIMeter.ReadOnly = true;

            //Общая сумма товара данного наименования в валюте
            GridViewDecimalColumn colAggrSumCur = new GridViewDecimalColumn("AGGR_SUM_CUR", dataSetFSO1.AGGR_PU_PAY_IN.PAY_SUM_CURColumn.ColumnName);
            colAggrSumCur.HeaderText = "Сумма (Вал.)";
            colAggrSumCur.FormatString = "{0:N2}";
            colAggrSumCur.Minimum = 0;
            colAggrSumCur.ReadOnly = true;

            //то же самое в рублях
            GridViewDecimalColumn colAggrSumRub = new GridViewDecimalColumn("AGGR_SUM_RUB", dataSetFSO1.AGGR_PU_PAY_IN.PAY_SUM_RUBColumn.ColumnName);
            colAggrSumRub.HeaderText = "Сумма";
            colAggrSumRub.FormatString = "{0:N2} Руб.";
            colAggrSumRub.Minimum = 0;


            //соединительная колонка
            GridViewTextBoxColumn colNSIProdId = new GridViewTextBoxColumn(dataSetFSO1.AGGR_PU_PAY_IN.NSI_PRODUCT_IDColumn.ColumnName);
            colNSIProdId.IsVisible = false;
            colNSIProdId.VisibleInColumnChooser = false;

            radGridViewItems.MasterTemplate.Columns.Clear();
            radGridViewItems.MasterTemplate.Columns.Add(colProdName);
            radGridViewItems.MasterTemplate.Columns.Add(colNSIProdId);
            radGridViewItems.MasterTemplate.Columns.Add(colCount);
            radGridViewItems.MasterTemplate.Columns.Add(colAggrNSIMeter);
            //radGridViewItems.MasterTemplate.Columns.Add(colAggrSumCur);
            radGridViewItems.MasterTemplate.Columns.Add(colAggrSumRub);

            radGridViewItems.MasterTemplate.EnableGrouping = false;
            //radGridViewItems.MasterTemplate.Columns.Add(colAggrButton);

            radGridViewItems.MasterTemplate.DataSource = dataSetFSO1.AGGR_PU_PAY_IN;


            //Таблица для единиц товара
            GridViewTemplate PUTemplate = new GridViewTemplate();

			//календарный план
			GridViewTextBoxColumn colCalendarPlan = new GridViewTextBoxColumn("PU_CALENDAR_PLAN", dataSetFSO1.VIEW_PAY_IN_ITEM.CALENDAR_PLAN_NUMBERColumn.ColumnName);
			colCalendarPlan.HeaderText = "Календарный план";
			colCalendarPlan.ReadOnly = true;

            GridViewTextBoxColumn colPUName = new GridViewTextBoxColumn("PU_NAME", dataSetFSO1.VIEW_PAY_IN_ITEM.PRODUCT_UNIT_NAMEColumn.ColumnName);
            colPUName.HeaderText = "Наименование";
            colPUName.ReadOnly = true;

            //Состояние товара, по нему будем группировать
            GridViewTextBoxColumn colPUState = new GridViewTextBoxColumn("PU_STATE", dataSetFSO1.VIEW_PAY_IN_ITEM.NSI_PRODUCT_STATE_NAMEColumn.ColumnName);
            colPUState.HeaderText = "Состояние";

            //Цена товара
            GridViewDecimalColumn colPUCost = new GridViewDecimalColumn("PU_Cost", dataSetFSO1.VIEW_PAY_IN_ITEM.PRODUCT_UNIT_COSTColumn.ColumnName);
            colPUCost.HeaderText = "Цена";
            colPUCost.FormatString = "{0:N2}";
            colPUCost.ReadOnly = true;

            //Сумма оплаты за товар в валюте
            GridViewDecimalColumn colPUSumCur = new GridViewDecimalColumn("PU_SUM_CUR", dataSetFSO1.VIEW_PAY_IN_ITEM.SUM_CURColumn.ColumnName);
            colPUSumCur.HeaderText = "Сумма оплаты (вал.)";
            colPUSumCur.FormatString = "{0:N2}";
            colPUSumCur.ReadOnly = true;
            //Валюта
            GridViewTextBoxColumn colPUCurName = new GridViewTextBoxColumn("PU_CURRENCY_NAME", dataSetFSO1.VIEW_PAY_IN_ITEM.NSI_CURRENCY_NAMEColumn.ColumnName);
            colPUCurName.HeaderText = "Вал.";
            colPUCurName.ReadOnly = true;

            //в рублях
            GridViewDecimalColumn colPUSumRub = new GridViewDecimalColumn("PU_SUM_RUB", dataSetFSO1.VIEW_PAY_IN_ITEM.SUM_RUBColumn.ColumnName);
            colPUSumRub.HeaderText = "Сумма оплаты";
            colPUSumRub.FormatString = "{0:N2} руб.";
            colPUSumRub.Minimum = 0;

            // % оплаты
            GridViewDecimalColumn colPUPerPay = new GridViewDecimalColumn("PU_PER_PAY", dataSetFSO1.VIEW_PAY_IN_ITEM.PAY_PERColumn.ColumnName);
            colPUPerPay.HeaderText = "% оплаты";
            colPUPerPay.FormatString = "{0:N2}%";
            colPUPerPay.ReadOnly = true;

            ////Сумма выставленных счетов на товар
            //GridViewDecimalColumn colPUInvOutSum = new GridViewDecimalColumn("PU_INV_IN_SUM", dataSetFSO1.VIEW_PAY_IN_ITEM.INVOICE_IN_SUMColumn.ColumnName);
            //colPUInvOutSum.HeaderText = "Выставлено счетов";
            //colPUInvOutSum.FormatString = "{0:N2}";

            ////№ и Название этапа Кп
            //GridViewTextBoxColumn colPUCPStageName = new GridViewTextBoxColumn("PU_CP_STAGE_NAME", dataSetFSO1.VIEW_PAY_IN_ITEM.CP_STAGE_NUMBERColumn.ColumnName);
            //colPUCPStageName.HeaderText = "Этап";

            //Конец этапа
            GridViewDateTimeColumn colPUCPEndDate = new GridViewDateTimeColumn("PU_CP_END_DATE", dataSetFSO1.VIEW_PAY_IN_ITEM.CP_STAGE_END_DATEColumn.ColumnName);
            colPUCPEndDate.HeaderText = "Отгрузка";
            colPUCPEndDate.FormatString = "{0:d}";
            colPUCPEndDate.ReadOnly = true;

            GridViewTextBoxColumn colVatInvNum = new GridViewTextBoxColumn("PU_VAT_INV_NUM", dataSetFSO1.VIEW_PAY_IN_ITEM.VAT_INVOICE_NUMBERColumn.ColumnName);
            colVatInvNum.HeaderText = "№ С-Ф";
            colVatInvNum.ReadOnly = true;

            //Дата счет-фактуры
            GridViewTextBoxColumn colVatInvDate = new GridViewTextBoxColumn("PU_VAT_INVOICE_DATE", dataSetFSO1.VIEW_PAY_IN_ITEM.VAT_INVOICE_DATE1Column.ColumnName);
            colVatInvDate.HeaderText = "Дата С-Ф";
            colVatInvDate.ReadOnly = true;
            //colVatInvDate.FormatString = "{0:d}";

            //№ счета
			GridViewTextBoxColumn colInvOutNum = new GridViewTextBoxColumn("PU_INVOICE_OUT_NUMBER", dataSetFSO1.VIEW_PAY_IN_ITEM.INVOICE_OUT_NUMBERColumn.ColumnName);
			colInvOutNum.HeaderText = "№ счета";
			colInvOutNum.ReadOnly = true;

            ////Дата платежа
            //GridViewTextBoxColumn colPayInDate = new GridViewTextBoxColumn("PU_PAYMENT_IN_ITEM_DATE", dataSetFSO1.VIEW_INV_OUT_ITEM.PAYMENT_IN_ITEM_DATEColumn.ColumnName);
            //colPayInDate.HeaderText = "Дата платежа";
            //colPayInDate.ReadOnly = true;

			//номер чертежа
			GridViewTextBoxColumn colDrawing = new GridViewTextBoxColumn("PU_N_DRAWING", dataSetFSO1.VIEW_PAY_IN_ITEM.N_DRAWINGColumn.ColumnName);
			colDrawing.HeaderText = "№ чертежа";
			colDrawing.ReadOnly = true;


            //Статус изделия
            GridViewTextBoxColumn colProductState = new GridViewTextBoxColumn("PU_NSI_PRODUCT_STATE_NAME", dataSetFSO1.VIEW_PAY_IN_ITEM.NSI_PRODUCT_STATE_NAMEColumn.ColumnName);
            colProductState.HeaderText = "Статус изделия";
            colProductState.ReadOnly = true;

			//Группа товара
			GridViewTextBoxColumn colProductGroup = new GridViewTextBoxColumn("PU_PROD_GROUP", dataSetFSO1.VIEW_PAY_IN_ITEM.PROD_GROUP_NAMEColumn.ColumnName);
			colProductGroup.HeaderText = "Группа товара";
			colProductGroup.ReadOnly = true;

            //Соединительное поле
            GridViewTextBoxColumn colPUNSIProdId = new GridViewTextBoxColumn(dataSetFSO1.VIEW_PAY_IN_ITEM.NSI_PRODUCT_IDColumn.ColumnName);
            colPUNSIProdId.IsVisible = false;
            colPUNSIProdId.VisibleInColumnChooser = false;
            colPUNSIProdId.ReadOnly = true;

            PUTemplate.Columns.Clear();
			PUTemplate.Columns.Add(colCalendarPlan);
            PUTemplate.Columns.Add(colPUName);
            PUTemplate.Columns.Add(colPUSumRub);
            PUTemplate.Columns.Add(colPUSumCur);
            PUTemplate.Columns.Add(colPUCurName);
            PUTemplate.Columns.Add(colPUCost);
            PUTemplate.Columns.Add(colPUPerPay);
            PUTemplate.Columns.Add(colPUCPEndDate);
            PUTemplate.Columns.Add(colVatInvNum);
            PUTemplate.Columns.Add(colVatInvDate);
            PUTemplate.Columns.Add(colInvOutNum);
            //PUTemplate.Columns.Add(colPayInDate);
			PUTemplate.Columns.Add(colDrawing);
            PUTemplate.Columns.Add(colProductState);
			PUTemplate.Columns.Add(colProductGroup);
            PUTemplate.Columns.Add(colPUNSIProdId);
            PUTemplate.DataSource = dataSetFSO1.VIEW_PAY_IN_ITEM;
            PUTemplate.ShowFilteringRow = false;
            PUTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
            PUTemplate.AllowAddNewRow = false;
            PUTemplate.AllowDeleteRow = false;

            radGridViewItems.Templates.Clear();
            radGridViewItems.Templates.Add(PUTemplate);

            GridViewRelation relation = new GridViewRelation(radGridViewItems.MasterTemplate, PUTemplate);
            relation.ParentColumnNames.Add(dataSetFSO1.AGGR_PU_PAY_IN.NSI_PRODUCT_IDColumn.ColumnName);
            relation.ChildColumnNames.Add(dataSetFSO1.VIEW_PAY_IN_ITEM.NSI_PRODUCT_IDColumn.ColumnName);
            relation.RelationName = "AGGREGATE_PRODUCTS";

            radGridViewItems.Relations.Clear();
            radGridViewItems.Relations.Add(relation);

            radGridViewItems.ShowGroupPanel = false;

        }

        private void IntializeServiceGrid()
        {
            GridViewTextBoxColumn colServName = new GridViewTextBoxColumn("SERVICE_NAME", dataSetFSO1.VIEW_PAY_IN_ON_SERVICE.NSI_SERVICE_NAMEColumn.ColumnName);
            colServName.HeaderText = "Наименование";
            colServName.ReadOnly = true;

            GridViewDecimalColumn colCount = new GridViewDecimalColumn("COUNT", dataSetFSO1.VIEW_PAY_IN_ON_SERVICE.QAUNTITYColumn.ColumnName);
            colCount.HeaderText = "Кол.";
            colCount.FormatString = "{0:N2}";
            //colCount.DecimalPlaces = 0;
            colCount.Minimum = 0;

            GridViewTextBoxColumn colMeter = new GridViewTextBoxColumn("NSI_METER_NAME", dataSetFSO1.VIEW_PAY_IN_ON_SERVICE.NSI_METER_NAMEColumn.ColumnName);
            colMeter.HeaderText = "Ед.";
            colMeter.ReadOnly = true;

            radGridViewItems.MasterTemplate.Columns.Clear();
            radGridViewItems.MasterTemplate.Columns.Add(colServName);
            radGridViewItems.MasterTemplate.Columns.Add(colCount);
            radGridViewItems.MasterTemplate.Columns.Add(colMeter);

            radGridViewItems.DataSource = dataSetFSO1.VIEW_PAY_IN_ON_SERVICE;

            radGridViewItems.EnableGrouping = false;
            radGridViewItems.ShowGroupPanel = false;
            radGridViewItems.AllowDragToGroup = false;

        }

        private void InitializePaymentsGrid()
        {
            GridViewTextBoxColumn colInvNum = new GridViewTextBoxColumn("INV_OUT_NUM", dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.INVOICE_OUT_NUMColumn.ColumnName);
            colInvNum.HeaderText = "№";
            colInvNum.ReadOnly = true;

            GridViewDecimalColumn colSumCur = new GridViewDecimalColumn("PAY_SUM_CUR", dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.SUM_CURColumn.ColumnName);
            colSumCur.HeaderText = "Сумма оплаты (вал.)";
            colSumCur.FormatString = "{0:N2}";
            colSumCur.ReadOnly = true;

            GridViewTextBoxColumn colCurrency = new GridViewTextBoxColumn("NSI_CUR_NAME", dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.NSI_CURRENCY_NAMEColumn.ColumnName);
            colCurrency.HeaderText = "Вал.";
            colCurrency.ReadOnly = true;

            GridViewDecimalColumn colSumRub = new GridViewDecimalColumn("PAY_SUM_RUB", dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.SUM_RUBColumn.ColumnName);
            colSumRub.HeaderText = "Сумма оплаты";
            colSumRub.FormatString = "{0:N2} руб.";

            radGridViewInvoices.MasterTemplate.Columns.Clear();

            radGridViewInvoices.MasterTemplate.Columns.Add(colInvNum);
            radGridViewInvoices.MasterTemplate.Columns.Add(colSumRub);
            radGridViewInvoices.MasterTemplate.Columns.Add(colSumCur);
            radGridViewInvoices.MasterTemplate.Columns.Add(colCurrency);
            
            radGridViewInvoices.DataSource = dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT;
            
        }

        private void FormPaymentIn_Load(object sender, EventArgs e)
        {
            if (_payInRow.TYPE == true)
            {
                //Событие на измение/добавление строки (пока используется только при добавлении товара)
                dataSetFSO1.VIEW_PAY_IN_ITEM.RowChanged += new DataRowChangeEventHandler(VIEW_PAY_IN_ITEM_RowChanged);
                
                //При из изменении кол-ва товара одного наименования
                dataSetFSO1.AGGR_PU_PAY_IN.ColumnChanged += new DataColumnChangeEventHandler(AGGR_PU_PAY_IN_ColumnChanged);

                //изменение валютной колонки при изменении рублевой
                dataSetFSO1.VIEW_PAY_IN_ITEM.ColumnChanged += new DataColumnChangeEventHandler(VIEW_PAY_IN_ITEM_ColumnChanged);
                dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.ColumnChanged += new DataColumnChangeEventHandler(VIEW_PAY_IN_ON_INV_OUT_ColumnChanged);
                
            }
            else if (_payInRow.TYPE == false)
            {
                radMaskedEditBoxAddPayPercent.Enabled = false;
                radMaskedEditBoxAdvancePercent.Enabled = false;
                radDropDownButtonAddFrom.Visible = false;
                radButtonAggrSum.Visible = false;
                radButtonNorma.Visible = false;
                radButtonEvaluateAdvace.Visible = false;
                panelRest.Visible = false;

                //изменение валютной колонки при изменении рублевой
                dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.ColumnChanged += new DataColumnChangeEventHandler(VIEW_PAY_IN_ON_INV_OUT_ColumnChanged);
            }

            radGridViewItems.MultiSelect = true;
            radGridViewInvoices.MultiSelect = true;
            radGridViewInvoices.EnableGrouping = false;

            RefreshForm();
        }

        #region События с таблицами датасета

        //изменение валютной колонки при изменении рублевой
        void VIEW_PAY_IN_ON_INV_OUT_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            if (e.Column == dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.SUM_RUBColumn)
            {
                DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow curRow = (DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow)e.Row;
                decimal rate = FormHelper.GetRate(curRow.NSI_CURRENCY_NAME, _payInRow.DATE);
                if (rate == 0)
                {
                    curRow.SUM_CUR = 0;
                }
                else
                {
                    curRow.SUM_CUR = curRow.SUM_RUB / rate;
                }
            }
        }

        //изменение валютной колонки при изменении рублевой
        void VIEW_PAY_IN_ITEM_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            if (e.Column == dataSetFSO1.VIEW_PAY_IN_ITEM.SUM_RUBColumn)
            { 
                DataSetFSO.VIEW_PAY_IN_ITEMRow curRow = (DataSetFSO.VIEW_PAY_IN_ITEMRow) e.Row;
                decimal rate = FormHelper.GetRate(curRow.NSI_CURRENCY_NAME, _payInRow.DATE);
                if (rate == 0)
                {
                    curRow.SUM_CUR = 0;
                }
                else
                {
                    curRow.SUM_CUR = curRow.SUM_RUB / rate;
                }
            }
        }
        //Настройка видимости агрегированной строки и общее изменение рублевой оплаты
        void AGGR_PU_PAY_IN_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            if (e.Column == dataSetFSO1.AGGR_PU_PAY_IN.COUNTColumn)
            {
                //MessageBox.Show(e.Action.ToString());
                DataSetFSO.AGGR_PU_PAY_INRow aggrPayRow = e.Row as DataSetFSO.AGGR_PU_PAY_INRow;
                //Выбираем соответсвующую строку из грида
                GridViewRowInfo rowInfo = (from rInf in radGridViewItems.MasterTemplate.Rows where ((int)rInf.Cells[dataSetFSO1.AGGR_PU_PAY_IN.NSI_PRODUCT_IDColumn.ColumnName].Value == aggrPayRow.NSI_PRODUCT_ID) select rInf).FirstOrDefault();
                if (rowInfo != null)
                {
                    if (aggrPayRow.COUNT < 1)
                    {
                        rowInfo.IsVisible = false;
                    }
                    else
                    {
                        rowInfo.IsVisible = true;
                    }
                }
            }
        }
        
        //действия при удалениии товара
        //void VIEW_PAY_IN_ITEM_RowDeleted(object sender, DataRowChangeEventArgs e)
        //{
        //    //DataSetFSO.VIEW_PAY_IN_ITEMRow rowPayInItem = e.Row as DataSetFSO.VIEW_PAY_IN_ITEMRow;
        //
        //    ////Получаем данные из оригинальной версии строки
        //    //int nsiProdId = 0;
        //    //if (rowPayInItem.RowState == DataRowState.Deleted)
        //    //{
        //    //    nsiProdId = (int)rowPayInItem[dataSetFSO1.VIEW_PAY_IN_ITEM.NSI_PRODUCT_IDColumn, DataRowVersion.Original];
        //    //}
        //    //else if (rowPayInItem.RowState == DataRowState.Detached)
        //    //{
        //    //    //rowPayInItem.SetAdded();
        //    //    rowPayInItem.AcceptChanges();
        //    //    nsiProdId = (int)rowPayInItem[dataSetFSO1.VIEW_PAY_IN_ITEM.NSI_PRODUCT_IDColumn, DataRowVersion.Default];
        //    //}

        //    //DataSetFSO.AGGR_PU_PAY_INRow aggrPayRow = (from aggrRow in dataSetFSO1.AGGR_PU_PAY_IN where (aggrRow.NSI_PRODUCT_ID == nsiProdId) select aggrRow).First();
        //    //aggrPayRow.COUNT--;
        //    
        //}

        void VIEW_PAY_IN_ITEM_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Add)
            {
                //MessageBox.Show("Добавляемся!!!");
                DataSetFSO.VIEW_PAY_IN_ITEMRow rowPayInItem = e.Row as DataSetFSO.VIEW_PAY_IN_ITEMRow;

                DataSetFSO.AGGR_PU_PAY_INRow aggrPayRow = (from aggrRow in dataSetFSO1.AGGR_PU_PAY_IN where (aggrRow.NSI_PRODUCT_ID == rowPayInItem.NSI_PRODUCT_ID) select aggrRow).FirstOrDefault();
                //Если такой записи нет а аггрегированной таблице
                if (aggrPayRow == null)
                {
                    aggrPayRow = dataSetFSO1.AGGR_PU_PAY_IN.NewAGGR_PU_PAY_INRow();
                    aggrPayRow.PAYMENT_IN_ID = _payInRow.ID;
                    aggrPayRow.NSI_METER_NAME = rowPayInItem.NSI_METER_NAME;
                    aggrPayRow.NSI_PRODUCT_ID = rowPayInItem.NSI_PRODUCT_ID;
                    if (rowPayInItem.NSI_PRODUCT_ID == -1)
                    {
                        //значит данный товар - работа
                        aggrPayRow.NAME = "Работы";
                    }
                    else
                    {
                        aggrPayRow.NAME = rowPayInItem.PRODUCT_UNIT_NAME;
                    }
                    dataSetFSO1.AGGR_PU_PAY_IN.AddAGGR_PU_PAY_INRow(aggrPayRow);
                }

                var rowDirectItem = rowPayInItem;

                DataSetFSO.AGGR_PRODUCT_UNTSRow aggrProductRow = (from aggrRow in dataSetFSO1.AGGR_PRODUCT_UNTS where (aggrRow.NSI_PRODUCT_ID == rowDirectItem.NSI_PRODUCT_ID) select aggrRow).FirstOrDefault();
                //Если такой записи нет а аггрегированной таблице
                if (aggrProductRow == null)
                {
                    aggrProductRow = dataSetFSO1.AGGR_PRODUCT_UNTS.NewAGGR_PRODUCT_UNTSRow();
                    //aggrProductRow. = _payInRow.ID;
                    aggrProductRow.NSI_METER_NAME = rowDirectItem.NSI_METER_NAME;
                    aggrProductRow.NSI_PRODUCT_ID = rowDirectItem.NSI_PRODUCT_ID;
                    if (rowDirectItem.NSI_PRODUCT_ID == -1)
                    {
                        //значит данный товар - работа
                        aggrProductRow.PRODUCT_UNIT_NAME = "Работы";
                    }
                    else
                    {
                        aggrProductRow.PRODUCT_UNIT_NAME = rowDirectItem.PRODUCT_UNIT_NAME;
                    }
                    dataSetFSO1.AGGR_PRODUCT_UNTS.AddAGGR_PRODUCT_UNTSRow(aggrProductRow);
                }

                aggrPayRow.COUNT++;
            }

        }

        #endregion

        //Возвращает выбранную строку (исх счет) с списке счетов
        public DataSetFSO.INVOICE_OUTRow SelectedInvoiceOutRow
        {
            get
            {
                DataSetFSO.INVOICE_OUTRow row;

                if (radGridViewInvoices.SelectedRows.Count > 0)
                {
                    DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow tmp;
                    INVOICE_OUTTableAdapter ta = new INVOICE_OUTTableAdapter();

                    tmp = (DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow)(((DataRowView)(radGridViewInvoices.SelectedRows.First()).DataBoundItem)).Row;
                    row = ta.GetDataByID(tmp.INVOICE_OUT_ID).FindByID(tmp.INVOICE_OUT_ID);
                }
                else
                {
                    row = null;
                }
                return row;
            }
        }

        private void radButtonDeleteOrg_Click(object sender, EventArgs e)
        {
            _payInRow.SetNSI_ORGANIZATION_IDNull();
            radLabelOrganization.Text = "<Не указана>";
        }

        private void radLabelOrganization_DoubleClick(object sender, EventArgs e)
        {
            if (_payInRow.IsNSI_ORGANIZATION_IDNull())
            {
                DialogFormSelectObject dialog = new DialogFormSelectObject(ObjctTypeEnum.ORGANIZATION);
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    DataSetFSO.NSI_ORGANIZATIONRow org = (DataSetFSO.NSI_ORGANIZATIONRow)dialog.SelectedRow;
                    _payInRow.NSI_ORGANIZATION_ID = org.ID;
                    radLabelOrganization.Text = org.SHORT_NAME;
                }
            }
            else
            {
                NSI_ORGANIZATIONTableAdapter ta = new NSI_ORGANIZATIONTableAdapter();
                DataSetFSO.NSI_ORGANIZATIONRow orgRow = ta.GetDataById(_payInRow.NSI_ORGANIZATION_ID).FindByID(_payInRow.NSI_ORGANIZATION_ID);
                FormNSIOrganization form = new FormNSIOrganization(orgRow);
                if (!FormHelper.HasOpenedForm(form.FormName))
                {
                    form.MdiParent = FormHelper.MainForm;
                    form.Show();
                    form.Select();
                }
            }
        }

        private void radButtonAddProducts_Click(object sender, EventArgs e)
        {

            //Если платеж не за услуги
            if (_payInRow.TYPE == true)
            {
                #region Добавление продуктов
                DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _payInRow.PID);
                if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    AddPUFromSelectDialog(selectPUDialog);
                }
                #endregion
            }
            //Если платеж за услуги
            else if (_payInRow.TYPE == false)
            {
                #region Добавление Услуг
                DialogFormSelectObject selectServiceDialog = new DialogFormSelectObject(ObjctTypeEnum.NSI_SERVICE);
                if (selectServiceDialog.ShowDialog() == DialogResult.OK)
                {
                    //selectPUDialog.SelectedRows
                    foreach (GridViewRowInfo rowInf in selectServiceDialog.SelectedRows)
                    {
                        DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                        if (drv != null && drv.Row is DataSetFSO.VIEW_SEARCH_NSI_SERVICERow)
                        {
                            DataSetFSO.VIEW_SEARCH_NSI_SERVICERow serviceRow = drv.Row as DataSetFSO.VIEW_SEARCH_NSI_SERVICERow;

                            try
                            {
                                DataSetFSO.VIEW_PAY_IN_ON_SERVICERow rowPayInOnServ = dataSetFSO1.VIEW_PAY_IN_ON_SERVICE.NewVIEW_PAY_IN_ON_SERVICERow();

                                rowPayInOnServ.PAYMENT_IN_ID = _payInRow.ID;
                                rowPayInOnServ.NSI_SERVICE_ID = serviceRow.ID;
                                
                                rowPayInOnServ.NSI_SERVICE_NAME = serviceRow.SHORT_NAME;
                                rowPayInOnServ.QAUNTITY = serviceRow.COUNT;                         
                                rowPayInOnServ.NSI_METER_NAME = serviceRow.NSI_METER_NAME;
                                

                                dataSetFSO1.VIEW_PAY_IN_ON_SERVICE.AddVIEW_PAY_IN_ON_SERVICERow(rowPayInOnServ);

                                ////Изменяем аггрегированную таблицу


                            }
                            catch (ConstraintException)
                            {
                                MessageBox.Show("Данная услуга уже добавлена к платежу!");
                            }
                        }
                    }
                }
                #endregion
            }
        }

        // Добавление продуктов из диалога выбора

        private void AddPUFromSelectDialog(DialogFormSelectObject selectPUDialog)
        {
            AddPUFromSelectDialog(selectPUDialog, null);
        }

        private void AddPUFromSelectDialog(DialogFormSelectObject selectPUDialog, int? invId)
        {
            foreach (GridViewRowInfo rowInf in selectPUDialog.SelectedRows)
            {
                DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                if (drv != null && drv.Row is DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow)
                {
                    DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow productUnitRow = drv.Row as DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow;

                    try
                    {
                        DataSetFSO.VIEW_PAY_IN_ITEMRow rowPayInItem = dataSetFSO1.VIEW_PAY_IN_ITEM.NewVIEW_PAY_IN_ITEMRow();

                        rowPayInItem.PAYMENT_IN_ID = _payInRow.ID;
                        rowPayInItem.PRODUCT_UNIT_ID = productUnitRow.ID;
                        rowPayInItem.CP_STAGE_ID = productUnitRow.CP_STAGE_ID;
                        if (!productUnitRow.IsNSI_PRODUCT_IDNull())
                        {
                            rowPayInItem.NSI_PRODUCT_ID = productUnitRow.NSI_PRODUCT_ID;
                        }
                        //значит это работа
                        else
                        {
                            rowPayInItem.NSI_PRODUCT_ID = -1;
                            //В базе это значение null поэтому приравниваем к единице
                            //productUnitRow.NSI_PRODUCT_ID = -1;
                        }
                        rowPayInItem.PRODUCT_UNIT_NAME = productUnitRow.NAME;
                        rowPayInItem.CP_STAGE_END_DATE = productUnitRow.CP_STAGE_END_DATE;
                        rowPayInItem.CP_STAGE_NUMBER = productUnitRow.CP_STAGE_NUMBER;
                        rowPayInItem.PRODUCT_UNIT_COST = productUnitRow.COST;
                        rowPayInItem.NSI_CURRENCY_NAME = productUnitRow.NSI_CURRENCY_NAME;
                        rowPayInItem.PAY_PER = productUnitRow.PAY_PER;
                        rowPayInItem.NSI_METER_NAME = productUnitRow.NSI_METER_NAME;
                        rowPayInItem.NSI_CURRENCY_NAME = productUnitRow.NSI_CURRENCY_NAME;
                        rowPayInItem.NSI_PRODUCT_STATE_ID = productUnitRow.NSI_PRODUCT_STATE_ID;
                        rowPayInItem.VAT_INVOICE_DATE1 = productUnitRow.VAT_INVOICE_DATE1;
                        rowPayInItem.NSI_PRODUCT_STATE_NAME = productUnitRow.NSI_PRODUCT_STATE_NAME;
						rowPayInItem.CALENDAR_PLAN_NUMBER = productUnitRow.CALENDAR_PLAN_NUMBER;
						rowPayInItem.INVOICE_OUT_NUMBER = productUnitRow.INVOICE_OUT_NUMBER;
						try
						{
							rowPayInItem.PROD_GROUP_NAME = productUnitRow.NSI_PROD_GROUP_NAME;
							rowPayInItem.N_DRAWING = productUnitRow.N_DRAWING;
						}
						catch { } //группа товара не указана либо это работы
                        if (invId.HasValue)
                        {
                            rowPayInItem.SUM_CUR = getSumCurFromInvoice(productUnitRow.ID, invId.Value);
                            rowPayInItem.SUM_RUB = rowPayInItem.SUM_CUR * FormHelper.GetRate(productUnitRow.NSI_CURRENCY_NAME, _payInRow.DATE);
                        }
                        

                        dataSetFSO1.VIEW_PAY_IN_ITEM.AddVIEW_PAY_IN_ITEMRow(rowPayInItem);

                       

                        ////Изменяем аггрегированную таблицу


                    }
                    catch (ConstraintException)
                    {
                        MessageBox.Show("Данный товар уже добавлен к платежу!");
                    }
                }
            }
        }

        private decimal getSumCurFromInvoice(int puId, int invId)
        {
            INVOICE_OUT_ITEMTableAdapter ta = new INVOICE_OUT_ITEMTableAdapter();

            return ta.GetDataByInvIdPuId(invId, puId).First().SUM;
        }

        //Добавление счета к платежу
        private void radButtonAddInv_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject selectInvOutDialog;
           
            if (_payInRow.TYPE == true)
            {
                
                selectInvOutDialog = new DialogFormSelectObject(ObjctTypeEnum.INVOICE_OUT, _payInRow.PID);
                
            }
            else
            {
                //Если платеж по услугам
                selectInvOutDialog = new DialogFormSelectObject(ObjctTypeEnum.INVOICE_OUT);

                (selectInvOutDialog.Control as UserControlSearchInvoiceOut).FillInvOnService();
            }

            if (selectInvOutDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                
                foreach (GridViewRowInfo rowInf in selectInvOutDialog.SelectedRows)
                {
                    DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                    if (drv != null && drv.Row is DataSetFSO.VIEW_SEARCH_INVOICE_OUTRow)
                    {
                        DataSetFSO.VIEW_SEARCH_INVOICE_OUTRow invOutRow = drv.Row as DataSetFSO.VIEW_SEARCH_INVOICE_OUTRow;

                        try
                        {
                            DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow payOnInv = dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.NewVIEW_PAY_IN_ON_INV_OUTRow();

                            payOnInv.PAYMENT_IN_ID = _payInRow.ID;
                            payOnInv.INVOICE_OUT_ID = invOutRow.ID;
                            payOnInv.INVOICE_OUT_NUM = invOutRow.NUMBER;
                            if (_payInRow.TYPE == true)
                            {
                                payOnInv.PID = _payInRow.PID;
                            }
                            payOnInv.NSI_CURRENCY_NAME = invOutRow.NSI_CURRENCY_SHORT_NAME;

                            dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.AddVIEW_PAY_IN_ON_INV_OUTRow(payOnInv);

                        }
                        catch (ConstraintException)
                        {
                            MessageBox.Show("Этот счет уже добавлен к платежу!");
                        }
                        
                    }
                }
                    
            }
        }

        //Удаление продукции
        private void radButtonDeleteProducts_Click(object sender, EventArgs e)
        {
            //Если платеж за продукты
            if (_payInRow.TYPE == true)
            {
                DataSetFSO.VIEW_PAY_IN_ITEMRow tmpPURow;
                foreach (GridViewRowInfo rowInf in radGridViewItems.SelectedRows.ToList())
                {
                    if ((tmpPURow = (rowInf.DataBoundItem as DataRowView).Row as DataSetFSO.VIEW_PAY_IN_ITEMRow) != null)
                    {

                        //Получаем данные из оригинальной версии строки
                        int nsiProdId = tmpPURow.NSI_PRODUCT_ID;
                        //PrintGrid();
                        DataSetFSO.AGGR_PU_PAY_INRow aggrPayRow = (from aggrRow in dataSetFSO1.AGGR_PU_PAY_IN where (aggrRow.NSI_PRODUCT_ID == nsiProdId) select aggrRow).First();
                        aggrPayRow.COUNT--;
                        rowInf.Delete();
                    }
                }
            }
            else if (_payInRow.TYPE == false)
            {
                foreach (GridViewRowInfo rowInf in radGridViewItems.SelectedRows.ToList())
                {
                    rowInf.Delete();
                }
            }
            
        }

        private void PrintGrid()
        {
            MessageBox.Show("ДатаСет - аггр");
            foreach (DataSetFSO.AGGR_PU_PAY_INRow row in dataSetFSO1.AGGR_PU_PAY_IN)
            {
                MessageBox.Show(row.NAME + " " + row.NSI_PRODUCT_ID.ToString());
            }
            MessageBox.Show("ДатаСет - unit");
            foreach (DataSetFSO.VIEW_PAY_IN_ITEMRow row in dataSetFSO1.VIEW_PAY_IN_ITEM)
            {
                MessageBox.Show(row.PRODUCT_UNIT_NAME + " " + row.NSI_PRODUCT_ID.ToString());
            }
            MessageBox.Show("Grid - aggr");
            foreach (GridViewRowInfo row in radGridViewItems.MasterTemplate.Rows)
            {
                MessageBox.Show(row.Cells[dataSetFSO1.AGGR_PU_PAY_IN.NSI_PRODUCT_IDColumn.ColumnName].Value.ToString()); //[dataSetFSO1.AGGR_PU_PAY_IN.NSI_PRODUCT_IDColumn.ColumnName]
            }
            try
            {
                MessageBox.Show("Grid - unit");
                foreach (GridViewRowInfo row in radGridViewItems.Templates[0].Rows)
                {
                    MessageBox.Show(row.Cells[dataSetFSO1.VIEW_PAY_IN_ITEM.NSI_PRODUCT_IDColumn.ColumnName].Value.ToString());
                }
            }
            catch
            { }
        }

        private void FormPaymentIn_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (!AllowSave)
				return;
            if (_payInRow.RowState != DataRowState.Deleted && _payInRow.RowState != DataRowState.Detached && (_payInRow.RowState == DataRowState.Added || _payInRow.RowState == DataRowState.Modified || (dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.GetChanges()) != null || (dataSetFSO1.VIEW_PAY_IN_ITEM.GetChanges()) != null || dataSetFSO1.VIEW_PAY_IN_ON_SERVICE.GetChanges() != null))
            {
                DialogResult result = MessageBox.Show(this, "Были внесены изменения. Сохранить?", "Сохранить изменения?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    int SaveResult = this.Save();

                    if (SaveResult == -1)
                    {
                        e.Cancel = true;
                    }
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
                else
                {
                    dataSetFSO1.RejectChanges();
                }
            }
        }

        //удаляет свзь со счетом
        private void radButtonDelInv_Click(object sender, EventArgs e)
        {
            foreach (GridViewRowInfo ri in radGridViewInvoices.SelectedRows.ToList())
            {
                if (ri != null)
                {
                    ri.Delete();
                }
            }
        }

        //Открывает договор
        private void radLabelContract_DoubleClick(object sender, EventArgs e)
        {
            if (!_payInRow.IsPIDNull())
            {
                CONTRACTTableAdapter ta = new CONTRACTTableAdapter();
                FormContract contractForm = new FormContract(ta.GetDataByPID(_payInRow.PID).First());
                if (!FormHelper.HasOpenedForm(contractForm.FormName))
                {
                    contractForm.MdiParent = FormHelper.MainForm;
                    contractForm.Show();
                    contractForm.Select();
                }
            }
        }

        //открывает выбранный счет
        private void radGridViewInvoices_CellDoubleClick(object sender, GridViewCellEventArgs e)
        {
            DataSetFSO.INVOICE_OUTRow invOutRow = this.SelectedInvoiceOutRow;
            if (invOutRow != null)
            {

                FormInvoiceOut formInvOut = new FormInvoiceOut(invOutRow);
                if (!FormHelper.HasOpenedForm(formInvOut.FormName))
                {
                    formInvOut.MdiParent = FormHelper.MainForm;
                    formInvOut.Show();
                    formInvOut.Select();
                }

            }
        }

        //Устанавливает среднюю цену для продукции с одним наименование исходя из агргированной таблицы
        private void radButtonNorma_Click(object sender, EventArgs e)
        {

            DataSetFSO.AGGR_PU_PAY_INRow tmpAggrPURow;
           
            foreach (GridViewRowInfo rowInf in radGridViewItems.SelectedRows.ToList())
            {
                if ((tmpAggrPURow = (rowInf.DataBoundItem as DataRowView).Row as DataSetFSO.AGGR_PU_PAY_INRow) != null)
                {
                    //Проходим по всем товарам с тем же NSI_PRODUCT_ID и устанавливаем среднюю цену и пересчитываем агрегированную валютную ячейку;
                    List<DataSetFSO.VIEW_PAY_IN_ITEMRow> payItems = (from row in dataSetFSO1.VIEW_PAY_IN_ITEM where row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached && row.NSI_PRODUCT_ID == tmpAggrPURow.NSI_PRODUCT_ID select row).ToList();
                    int itemCount = payItems.Count;
                    tmpAggrPURow.PAY_SUM_CUR = 0;
                    for (int i = 0; i < itemCount; i++)
                    {
                        //Приравниваем к среднему значению
                        payItems[i].SUM_RUB = tmpAggrPURow.PAY_SUM_RUB / itemCount;
                        //Пересчет валютной ячейки
                        tmpAggrPURow.PAY_SUM_CUR += payItems[i].SUM_CUR;
                    }
                }
            }
        }

        //Суммирует все платежи
        private void radButtonAggrSum_Click(object sender, EventArgs e)
        {
            PaySummary();
        }

        //Пересчет агрегированных сумм
        private void PaySummary()
        {
            foreach (DataSetFSO.AGGR_PU_PAY_INRow tmpAggrPURow in dataSetFSO1.AGGR_PU_PAY_IN.Rows)
            {
                //Проходим по всем товарам с тем же NSI_PRODUCT_ID и устанавливаем складываем цену;
                List<DataSetFSO.VIEW_PAY_IN_ITEMRow> payItems = (from row in dataSetFSO1.VIEW_PAY_IN_ITEM where row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached && row.NSI_PRODUCT_ID == tmpAggrPURow.NSI_PRODUCT_ID select row).ToList();
                int itemCount = payItems.Count;

                tmpAggrPURow.PAY_SUM_RUB = 0;
                tmpAggrPURow.PAY_SUM_CUR = 0;
                for (int i = 0; i < itemCount; i++)
                {
                    tmpAggrPURow.PAY_SUM_RUB += payItems[i].SUM_RUB;
                    tmpAggrPURow.PAY_SUM_CUR += payItems[i].SUM_CUR;
                }
            }
        }

        private void radButtonEvaluateAdvace_Click(object sender, EventArgs e)
        {
            EvaluateAdvance();
        }

        //Пересчет процентов аванса и доплаты
        private void EvaluateAdvance()
        {
            decimal advance = 0;
            decimal payAdd = 0;
            int advanceIter = 0;
            int payAddIter = 0;
            foreach (DataSetFSO.VIEW_PAY_IN_ITEMRow row in dataSetFSO1.VIEW_PAY_IN_ITEM.Rows)
            {
                if (row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached)
                {
                    decimal sum = 0;
                    //try
                    //{
                    //    //Узнаем сумму платежей на этот товар до даты текущего платежа
                    //    sum = (decimal)vieW_PAY_IN_ITEMTableAdapter1.getPaySumCurByDate(row.PRODUCT_UNIT_ID, _payInRow.DATE);
                    //}
                    //catch (InvalidOperationException)
                    //{
                    //    //Значит не было платежей
                    //    sum = 0;
                    //}

                    sum += row.SUM_CUR;

                    switch (row.NSI_PRODUCT_STATE_ID)
                    {
                        case 1:
                        case 2:
                            advanceIter++;
                            advance += sum / row.PRODUCT_UNIT_COST;
                            //advance = ((advanceIter - 1) * advance + (sum / row.PRODUCT_UNIT_COST)) / advanceIter;
                            break;
                        case 3:
                        case 4:
                            payAddIter++;
                            payAdd += sum / row.PRODUCT_UNIT_COST;
                            //payAdd = ((payAddIter - 1) * payAdd + (sum / row.PRODUCT_UNIT_COST)) / payAddIter;
                            break;
                        default:
                            break;

                    }
                    //MessageBox.Show(sum.ToString());
                }
            }
            if (advanceIter != 0)
                advance = 100 * advance / advanceIter;
            if (payAddIter != 0)
                payAdd = 100 * payAdd / payAddIter;
            radMaskedEditBoxAdvancePercent.Text = String.Format("{0:N2}%", advance);
            radMaskedEditBoxAddPayPercent.Text = String.Format("{0:N2}%", payAdd);
        }

        //Пересчет неизрасходованных средств
        private void EvaluateRests()
        {
            decimal productRest = _payInRow.SUM_RUB;
            decimal invoiceRest = _payInRow.SUM_RUB;

            foreach (DataSetFSO.VIEW_PAY_IN_ITEMRow row in dataSetFSO1.VIEW_PAY_IN_ITEM.Rows)
            {
                if (row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached)
                {
                    productRest -= row.SUM_RUB;
                }
            }

            foreach (DataSetFSO.VIEW_PAY_IN_ON_INV_OUTRow row in dataSetFSO1.VIEW_PAY_IN_ON_INV_OUT.Rows)
            {
                if (row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached)
                {
                    invoiceRest -= row.SUM_RUB;
                }
            }

            radLabelInvoiceRest.Text = String.Format("{0:N2} Руб.", invoiceRest);
            radLabelProductRest.Text = String.Format("{0:N2} Руб.", productRest);
        }

        //Вычисление остатков
        private void radButtonEvaluateRest_Click(object sender, EventArgs e)
        {
            EvaluateRests();
        }

        //Добавление товаров из определенного счета
        private void radMenuItemAddFromInv_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject selectInvOutDialog = new DialogFormSelectObject(ObjctTypeEnum.INVOICE_OUT, _payInRow.PID);
            DataSetFSO.INVOICE_OUTRow invOut;
            if (selectInvOutDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && (invOut = selectInvOutDialog.SelectedRow as DataSetFSO.INVOICE_OUTRow) != null)
            {
                DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _payInRow.PID);
                (selectPUDialog.Control as UserControlSearchPrUnitByID).FillGridByInvoiceOutID(invOut.ID);

                if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    AddPUFromSelectDialog(selectPUDialog, invOut.ID);
                    PaySummary();
                }

            }
        }

        //Добавление товаров из определенной счет-фактуры
        private void radMenuItemVatInvoice_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject selectInvOutDialog = new DialogFormSelectObject(ObjctTypeEnum.VAT_INVOICE, _payInRow.PID);
            DataSetFSO.VAT_INVOICERow vatInv;
            if (selectInvOutDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && (vatInv = selectInvOutDialog.SelectedRow as DataSetFSO.VAT_INVOICERow) != null)
            {
                DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _payInRow.PID);
                (selectPUDialog.Control as UserControlSearchPrUnitByID).FillGridByVatInvoiceID(vatInv.ID);

                if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    AddPUFromSelectDialog(selectPUDialog);
                }

            }
        }

		public bool AllowSave;
	}
}
